import { defineStore } from 'pinia'
import { LocalStorage } from 'quasar';
import { axiosLocal } from 'boot/axios';
import md5 from 'md5';

export const useStore = defineStore('store', {
  state: () => ({
    secretKey: 'MDY20240826', // 加密路径中id的key
    dictionary: {}, // 数据字典
    scrollTop: 0, // 和顶部的距离
    searchParam: {}, // 搜索参数
    siteConfig: {}, // 网站配置
    defaultImg: [{ image: '/images/default_img.jpg', thumb: '/images/default_img.jpg' }],
    defaultHeadImg: '/images/avatar.png',
    menuInfo: { menu: [], rightItem: [] }, // 菜单信息
    taskSwap: {} // 任务交换区
    // userMenu: []
  }),

  getters: {
    siteInfo: state => state.siteConfig,
    dictObj: state => { //  把字典的数组转成对应
      const dictObj = {};
      for (const key in state.dictionary) {
        dictObj[key] = {};
        state.dictionary[key].forEach(v => {
          dictObj[key][v.value] = Object.assign({}, v);
        });
      }

      return dictObj;
    },
    userInfo: state => {
      const tenant = LocalStorage.getItem('tenant');
      const user = LocalStorage.getItem('user');
      const role = LocalStorage.getItem('role');

      return {
        tenant_id: tenant.id,
        tenant_name: tenant.tenant_name,
        tenant_company: tenant.company,
        user_id: user.id,
        nickname: user.nickname,
        rights: user.rights,
        role_id: role.id,
        role_name: role.role_name
      }
    },
    menuObj: state => { // 把菜单转成object
      const menu = {};
      for (const row of state.menuInfo.menu.filter(v => v.type === 'menu')) {
        menu[row.name] = {
          value: row.name,
          label: row.caption,
          icon: row.icon
        }
      }
      return menu;
    },
    signUID: state => {
      const user = LocalStorage.getItem('user');
      return md5(`user_${user.id}_${state.secretKey}`)
    },
    rights: state => {
      const user = LocalStorage.getItem('user');
      return user.rights;
    }
  },

  actions: {
    initDictionary (dict) {
      this.dictionary = { ...this.dictionary, ...dict };
    },
    saveScrollTop () {
      this.scrollTop = document.documentElement.scrollTop;
    },
    restoreScrollTop () {
      const top = this.scrollTop;
      this.scrollTop = 0;
      const timer = setInterval(() => {
        if (document.readyState === 'complete') {
          setTimeout(() => {
            window.scrollTo(0, top);
          }, 500);

          window.clearInterval(timer)
        }
      }, 100);
    },
    saveSearchParam (param) {
      this.searchParam = { ...this.searchParam, ...param }
    },
    setSiteConfig (config) {
      this.siteConfig = config;
    },
    setMenuInfo (menuInfo) {
      this.menuInfo = menuInfo;
    },
    setUserMenu (menu) {
      this.userMenu = menu;
    },
    setGeneral (general) {
      this.general = general;
    },
    async fetchSiteConfig () { // 预取网站配置
      return new Promise(resolve => {
        // 取网站配置信息
        axiosLocal.get('/c/system/getSiteConfig').then(({ data }) => {
          this.siteConfig = data.site;
          resolve();
        });
      });
    },
    setTask (type, tasks) { // 任务写入交换区
      this.taskSwap[type] = tasks;
    },
    getTask (type, clear = true) { // 取任务，取完后清除
      const tasks = this.taskSwap[type];
      if (clear && this.taskSwap[type]) delete this.taskSwap[type];
      return tasks;
    }
  }
})
